from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from celery_tasks.sms.tasks import send_sms_code
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE


class ImageView(View):
    def get(self,request,uuid):
        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s'%uuid,120,text)
        return http.HttpResponse(image,content_type='image/jpeg')

class Sms_Code(View):
    def get(self,request,mobile):
        image_code_html = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([mobile,image_code_html,uuid]):
           return http.JsonResponse({"code":RETCODE.NECESSARYPARAMERR,'errmsg':'参数不齐'})

        redis_conn = get_redis_connection('code')
        text_redis = redis_conn.get('img_%s'%uuid)

        if text_redis is None:
           return http.JsonResponse({"code":RETCODE.NECESSARYPARAMERR,'errmsg':'验证码过期了'})


        redis_conn.delete('img_%s'%uuid)
        if text_redis.decode().lower() != image_code_html.lower():
            return http.JsonResponse({"code":RETCODE.IMAGECODEERR,'errmsg':'图片验证码错误'})
        # 判断是否重复操作
        send_flag = redis_conn.get('send_falg_%s'%mobile)
        if send_flag:
            return http.JsonResponse({"code":RETCODE.THROTTLINGERR,'errmsg':'发送太频繁了'})

        from random import randint
        sms_code = '%06d'%randint(0,99999)
        #
        # redis_conn.setex('sms_%s'%mobile,600,sms_code)
        # redis_conn.setex('send_flag_%s'%mobile,60,1)
        pipe = redis_conn.pipeline()

        pipe.setex('sms_%s'%mobile,600,sms_code)
        pipe.setex('send_flag_%s'%mobile,60,1)

        pipe.execute()

        # 实现异步发送短信
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        send_sms_code.delay(mobile,sms_code)

        return http.JsonResponse({"code":RETCODE.OK,'errmsg':'ok'})